package daobeauty.interceptor.invoke.impl;

import java.lang.reflect.Method;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;

import daobeauty.dao.SessionFactoryAware;
import daobeauty.interceptor.invoke.InvokeStrategy;
import daobeauty.util.MethodSignatureUtils;

public class DelegateInvoke implements InvokeStrategy {
	private static final Log LOG = LogFactory.getLog(DelegateInvoke.class);
	private final Object delegate;
	private final Method delegateMethod;
	
	public DelegateInvoke(Object delegate, Method delegateMethod, SessionFactory sessionFactory) {
		this.delegate = delegate;
		this.delegateMethod = delegateMethod;
		if (LOG.isInfoEnabled()){
			LOG.info("created delegate invoke strategy with delegate class "+delegate.getClass().getName()+" for method "+MethodSignatureUtils.toMethodSignature(delegateMethod));
		}
		if (SessionFactoryAware.class.isAssignableFrom(delegate.getClass())){
			final SessionFactoryAware sfa = (SessionFactoryAware) delegate;
			if (sfa.getSessionFactory()==null){
				sfa.setSessionFactory(sessionFactory);
			}
		}
	}
	
	public Object invoke(String methodName, Object[] args) throws Exception{
		return delegateMethod.invoke(delegate, args);
	}
}
